from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont
import os

def image_add_text(path: str, text: str,file_name: int, font_size: int=50, border_heavy: int=2):
    """
    path: 文件地址
    text: 文案内容
    file_name: 文件名称
    font_size: 字号 默认 50
    border_heavy: 描边宽度 默认 2px
    图片添加文案
    """
    image_path = path
    font = './video_to_images/jiyinghuipianheyuan.ttf'  # 字体文件
    font_size = font_size

    img = Image.open(image_path)    # 打开图像
    draw = ImageDraw.Draw(img)      # 新建画布

    font_text = ImageFont.truetype(font, font_size)  # 新建可操作字体

    img_size = img.size     # 获取图像尺寸
    text_color = (255, 255, 255)    # 文案颜色

    # 确定文案尺寸
    text_size = draw.textsize(text, font=font_text)
    text_x = (img_size[0] - text_size[0]) / 2
    text_y = img_size[1] - 90

    border_color = (0, 0, 0)    # 文字描边颜色

    # 绘制边框（上下左右）
    draw.text(xy=(text_x - border_heavy, text_y), text=text, font=font_text, fill=border_color)
    draw.text(xy=(text_x + border_heavy, text_y), text=text, font=font_text, fill=border_color)
    draw.text(xy=(text_x, text_y - border_heavy), text=text, font=font_text, fill=border_color)
    draw.text(xy=(text_x, text_y + border_heavy), text=text, font=font_text, fill=border_color)
    # 绘制边框（左上右上，左下右下）
    draw.text(xy=(text_x - border_heavy, text_y - border_heavy), text=text, font=font_text, fill=border_color)
    draw.text(xy=(text_x + border_heavy, text_y - border_heavy), text=text, font=font_text, fill=border_color)
    draw.text(xy=(text_x - border_heavy, text_y + border_heavy), text=text, font=font_text, fill=border_color)
    draw.text(xy=(text_x + border_heavy, text_y + border_heavy), text=text, font=font_text, fill=border_color)

    # 图文合并
    draw.text((text_x, text_y), text, fill=text_color, font=font_text)
    os.remove(path=path)
    img.save('./images/'+str(file_name)+'_text.jpeg')

def add_text_to_images()->None:
    path = './images/'
    files_list = os.listdir(path=path)
    images_name = list()
    for file in files_list:
        if '.jpeg' in file:
            images_name.append(file)
    images_name.sort(key=lambda x: int(x.split('_')[0]))
    text_list = list()
    with open('./video_to_images/texts.txt') as fr:
        for text in fr.readlines():
            text_list.append(text.replace('\n', ''))
    text_index = 0
    for file in images_name:
        print(file)
        if '.jpeg' in file and text_index<len(text_list):
            image_add_text(path=path+file, text=text_list[text_index],file_name=text_index+1)
            text_index += 1
    print('>>> Step.4 全部图像已成功添加文案.')

add_text_to_images()